package com.qzl.common.netty.handler;

import com.qzl.common.netty.annotation.MessageType;
import org.reflections.Reflections;

import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author: qzl
 * @date : 2025/6/24 8:52
 * @description: 策略生产工厂
 */
public class MessageFactory {
    //我们将策略类存入HashMap里面
    private static Map<Integer, MessageHandler> map = new ConcurrentHashMap<>();

    //根据command获取对应的策略类
    public static MessageHandler getInvokeStrategy(Integer messageType){
        return map.get(messageType);
    }
    // 注册所有策略
    static {
        Reflections reflections = new Reflections("com.qzl.common.netty.handler.strategy"); // 替换为你的策略实现类所在包
        Set<Class<? extends MessageHandler>> messageHandlerClasses = reflections.getSubTypesOf(MessageHandler.class);

        for (Class<? extends MessageHandler> clazz : messageHandlerClasses) {
            if (clazz.isAnnotationPresent(MessageType.class)) {
                MessageType annotation = clazz.getAnnotation(MessageType.class);
                int messageType = annotation.messageType();
                try {
                    map.put(messageType, clazz.getDeclaredConstructor().newInstance());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
